import axios from 'axios'
import { useMainStore } from '@/stores/main'
import router from '../router'
import { requestOptions } from './configs'
import createMessage from '@/components/CreateMessage'

// 模式，判断模式是不是mock
const mode = import.meta.env.VITE_MOCK
// axios基本配置
const service = axios.create({
  baseURL: requestOptions.url,
})
// 请求拦截
service.interceptors.request.use((config) => {
  const url = config.url
  // const unSupportWithMock = /^\/[(upload)()]$/
  if (url && /^\/upload$/.test(url)) {
    createMessage('mock模式下不支持文件上传功能', 'default', 2000)
    return
  }
  const store = useMainStore()
  store.isLoading = true
  store.error = { status: false, message: '' }
  console.log('request', config)

  return config
})
// 响应拦截
service.interceptors.response.use(
  (config) => {
    const store = useMainStore()
    store.isLoading = false
    if (config) {
      // console.log('response config', config)
    }
    return config
    // 非(>=200 && <300)会拦截进err中
  },
  (err) => {
    const store = useMainStore()
    const error = err.response.data // 请求错误
    store.isLoading = false
    store.error = { status: true, message: error }
    console.log(error)
    // 无效token —— 10006 或者 token —— 10005 过期的情况 或者 10002 用户不存在
    if (error && error.code === 10005) {
      router.push('/login')
      store.logout()
    }
    // if (error.code === 401) {
    //   router.push('/login')
    //   store.logoutAction()
    // }
    return Promise.reject(error)
  }
)
export default service
